package vip.liux.backend.adapter.web;


import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import vip.liux.backend.application.service.pay.PayChannelService;
import vip.liux.backend.application.service.pay.dto.channel.PayChannelCreateDto;
import vip.liux.backend.application.service.pay.dto.channel.PayChannelDto;
import vip.liux.backend.application.service.pay.dto.channel.PayChannelUpdateDto;
import vip.liux.contracts.shared.enums.Status;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/pay/channel")
public class PayChannelController {

    @Resource
    private PayChannelService channelService;

    /**
     * 创建支付渠道
     *
     * @param createDto 创建参数
     * @return 创建的支付渠道信息
     */
    @PostMapping
    public PayChannelDto createChannel(@Valid @RequestBody PayChannelCreateDto createDto) {
        return channelService.createChannel(createDto);
    }


    /**
     * 更新支付渠道
     *
     * @param id        渠道编号
     * @param updateDto 更新参数
     * @return 更新后的支付渠道信息
     */
    @PutMapping("/{id}")
    public PayChannelDto updateChannel(@PathVariable Long id, @Valid @RequestBody PayChannelUpdateDto updateDto) {
        return channelService.updateChannel(id, updateDto);
    }

    /**
     * 删除支付渠道
     *
     * @param id 渠道编号
     */
    @DeleteMapping("/{id}")
    public void deleteChannel(@PathVariable("id") Long id) {
        channelService.deleteChannel(id);
    }

    /**
     * 获取支付渠道
     *
     * @param id    渠道编号
     * @param appId 应用编号
     * @param code  渠道代码
     * @return 支付渠道信息
     */
    @GetMapping({"/{id}", ""})
    public PayChannelDto getChannel(
            @PathVariable(value = "id", required = false) Long id,
            @RequestParam(value = "appId", required = false) Long appId,
            @RequestParam(value = "code", required = false) String code) {
        PayChannelDto channel = null;
        if (id != null) {
            channel = channelService.getChannel(id);
        } else if (appId != null && code != null) {
            channel = channelService.getChannelByAppIdAndCode(appId, code);
        }
        return channel;
    }

    /**
     * 获取指定应用的启用的支付渠道编码列表
     *
     * @param appId 应用编号
     * @return 启用的支付渠道编码列表
     */
    @GetMapping("/{appId}/enable-code-list")
    public Set<String> getEnableChannelCodeList(@PathVariable("appId") Long appId) {
        List<PayChannelDto> channels = channelService.getEnableChannelList(appId).getItems();
        return channels.stream().filter(c -> c.getStatus() == Status.ENABLED).map(PayChannelDto::getCode).collect(Collectors.toSet());
    }
}
